﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Smatime.Web.DAO;
using Smatime.Web.Models;

namespace Smatime.Web.Controllers
{
    public class CompanyStaffTimeTableController : ApiController
    {
        // GET api/companystafftimetable
        public IEnumerable<CompanyStaffTimeTable> Get()
        {
            return new CompanyStaffTimeTableRepository().GetList();
        }

        // GET api/companystafftimetable/5
        public CompanyStaffTimeTable Get(int id)
        {
            return new CompanyStaffTimeTableRepository().GetById(id);
        }
        // GET api/companystafftimetable/5
        [Route("api/companystafftimetable/{storeId}/{month}")]
        public HttpResponseMessage Get(int storeId, int month)
        {
            try
            {
                var results = new CompanyStaffTimeTableRepository().GetCompanyStaffTimeTable(storeId, month);
                return Request.CreateResponse(HttpStatusCode.OK, results);
            }
            catch (Exception exception)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, exception);
            }
        }

        /// <summary>
        ///     POST api/companystafftimetable
        ///     Add new row for CompanyStaffTimeTable
        /// </summary>
        /// <param name="value"></param>
        public HttpResponseMessage Post([FromBody] CompanyStaffTimeTable value)
        {
            try
            {
                var repos = new CompanyStaffTimeTableRepository();
                var companyStaffCheckInRepos = new ListCompanyStaffCheckInRepository();
                var updateStaff = companyStaffCheckInRepos.GetByCompanyId(value.CompanyStaffId).ToList();
                CompanyStaffTimeTable companyStaffTimeTable;
                if (updateStaff.Count == 0)
                {
                    repos.Insert(value);
                    updateStaff = companyStaffCheckInRepos.GetByCompanyId(value.CompanyStaffId).ToList();
                    companyStaffTimeTable = updateStaff.FirstOrDefault();
                    return companyStaffTimeTable != null
                        ? Request.CreateResponse(HttpStatusCode.OK)
                        : Request.CreateResponse(HttpStatusCode.BadRequest);
                }
                companyStaffTimeTable = updateStaff.FirstOrDefault();
                if (companyStaffTimeTable == null)
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest);
                }
                value.Id = companyStaffTimeTable.Id;
                repos.Update(value);
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, ex);
            }
        }
    }
}